/**
 * @FileName: ScreenUtil.java  
 * @Package:com.liaofan.android.diandi.util.UI  
 * @Description: TODO 
 * @author: huangyuan   
 * @date:2014年10月24日 下午2:38:46  
 * @version V1.0   
 */
package com.cdut.hezhisu.dribbble.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.res.Configuration;
import android.os.PowerManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;


import com.cdut.hezhisu.dribbble.DribbbleApp;

import java.lang.reflect.Field;

/**
 * @ClassName: ScreenUtil  
 * @Description: TODO 
 * @author: huangyuan 
 * @date:2014年10月24日 下午2:38:46  
 */
@SuppressLint("NewApi") public class ScreenUtil {

	
	
	/**
	 * 
	 * @Title: isTelephoneLock  
	 * @Description: 判断手机是否锁屏;
	 * @param context
	 * @return boolean 
	 * @throws
	 */
    public static boolean isTelephoneLock(Context context){
        KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        return mKeyguardManager.inKeyguardRestrictedInputMode();
    }
    
    
    /**
     * 
     * @Title: isTelephoneScreenOn  
     * @Description: 判断手机屏幕是否点亮;
     * @param context
     * @return boolean 
     * @throws
     */
    public static boolean isTelephoneScreenOn(Context context){
        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
        return pm.isScreenOn();
    }
    
    
	/**
	 * 
	 * @Title: getStatusBarHeight  
	 * @Description: 获取状态栏高度; 
	 * @param context
	 * @return int 
	 * @throws
	 */
	public static int getStatusBarHeight(Context context){
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        } 
        return statusBarHeight;
	 }
	
	
	/**
	 * 
	 * @Title: getScreenResolution  
	 * @Description: 获取设备的分辨率;
	 * @param ctx
	 * @return String 字符串类型 如：480*800;
	 * @throws
	 */
	public static String getScreenResolution(Context ctx) {
		DisplayMetrics metrics = new DisplayMetrics();
		WindowManager windowManager = (WindowManager) ctx
				.getApplicationContext().getSystemService(
						Context.WINDOW_SERVICE);
		windowManager.getDefaultDisplay().getMetrics(metrics);
		int width = metrics.widthPixels < metrics.heightPixels ? metrics.widthPixels : metrics.heightPixels;
		int height = metrics.widthPixels < metrics.heightPixels ? metrics.heightPixels : metrics.widthPixels;
		//String resolution = width + "x" + height;
		String resolution = width + "*" + height;
		return resolution;
	}
	
	
	/**
	 * 
	 * @Title: getScreenResolutionXY  
	 * @Description: 返回屏幕分辨率,数组型。width小于height
	 * @param ctx
	 * @return int[] 
	 * @throws
	 */
	public static int[] getScreenResolutionXY(Context ctx) {
		int[] resolutionXY = new int[2];
		if (resolutionXY[0] != 0) {
			return resolutionXY;
		}
		DisplayMetrics metrics = new DisplayMetrics();
		WindowManager windowManager = (WindowManager) ctx
				.getApplicationContext().getSystemService(
						Context.WINDOW_SERVICE);
		windowManager.getDefaultDisplay().getMetrics(metrics);
		resolutionXY[0] = metrics.widthPixels < metrics.heightPixels ? metrics.widthPixels : metrics.heightPixels;
		resolutionXY[1] = metrics.widthPixels < metrics.heightPixels ? metrics.heightPixels : metrics.widthPixels;
		return resolutionXY;
	}
	
	
	/**
	 * 
	 * @Title: getScreenDensity  
	 * @Description: 返回屏幕像素密度;
	 * @param ctx 
	 * @return float 
	 * @throws
	 */
	public static float getScreenDensity(Context ctx) {
		return ctx.getResources().getDisplayMetrics().density;
	}
	
	
	/**
	 * 
	 * @Title: getDisplayMetrics  
	 * @Description: 返回屏幕尺寸
	 * @param context 
	 * @return DisplayMetrics 
	 * @throws
	 */
	public static DisplayMetrics getDisplayMetrics(Context context) {
		return context.getResources().getDisplayMetrics();
	}
	
	
	/**
	 * 
	 * @Title: getScreenWidth  
	 * @Description:  获取屏幕宽度;
	 * @param context
	 * @return int 
	 * @throws
	 */
	public static int getScreenWidth(Context context) {
		DisplayMetrics metrics = getDisplayMetrics(context);
		return metrics.widthPixels > metrics.heightPixels? metrics.heightPixels: metrics.widthPixels;
	}
	
	
	/**
	 * 
	 * @Title: getScreenHeight  
	 * @Description: 获取屏幕高度;
	 * @param context 
	 * @return int 
	 * @throws
	 */
	public static int getScreenHeight(Context context) {
		DisplayMetrics metrics = getDisplayMetrics(context);
		return metrics.heightPixels;
	}
	
	/**
	 * 
	 * @Title: isOrientationLandscape  
	 * @Description: 判断屏幕是否为横屏; 
	 * @param context
	 * @return boolean 
	 * @throws
	 */
	public static boolean isOrientationLandscape(Context context) {
		if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			return true;
		}
		return false;
	}
	
	
	/**
	 * 
	 * @Title: dip2dpx  
	 * @Description:   
	 * @param dipValue 
	 * @return int 
	 * @throws
	 */
	public static int dip2px(float dipValue){
		
		final float scale = DribbbleApp.mAppContext.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}
	
	
	/**
	 * 
	 * @Title: px2dip  
	 * @Description: TODO 
	 * @param pxValue
	 * @return int 
	 * @throws
	 */
	public static int px2dip(float pxValue){
		
		final float scale = DribbbleApp.mAppContext.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
	
	/**
	 * 
	 * @Title: dip2px  
	 * @Description: 将像dip转换成px; 
	 * @param context
	 * @param dipValue 
	 * @return int 
	 * @throws
	 */
	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}


	/**
	 * 
	 * @Title: px2dip  
	 * @Description: 将px转换成dip; 
	 * @param context
	 * @param pxValue 
	 * @return int 
	 * @throws
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}


	/**
	 * @Title px2sp
	 * @deprecated:将px换成sp;
	 * @param context
	 * @param pxValue 
	 * @return
	 */
	public static int px2sp(Context context, float pxValue){
		
		return (int) (pxValue/getScreenDensity(context));
	}
	
	
	/**
	 * 
	 * @Title: dip2px  
	 * @Description: 将dip转换成px; 
	 * @param metrics
	 * @param dipValue 
	 * @return int 
	 * @throws
	 */
	public static int dip2px(DisplayMetrics metrics, float dipValue) {
		final float scale = metrics.density;
		return (int) (dipValue * scale + 0.5f);
	}

	
	/**
	 * 
	 * @Title: px2dip  
	 * @Description: 将px装换成dip; 
	 * @param metrics
	 * @param pxValue
	 * @return int 
	 * @throws
	 */
	public static int px2dip(DisplayMetrics metrics, float pxValue) {
		final float scale = metrics.density;
		return (int) (pxValue / scale + 0.5f);
	}
	
	/**
	 * 显示输入法
	 * @param c
	 * @param view
	 */
	public static void input_method_show(Context c,View view){
		view.setFocusable(true);  
		view.setFocusableInTouchMode(true);  
		view.requestFocus();  
		view.findFocus();
		InputMethodManager inputManager = (InputMethodManager)c.getSystemService(Context.INPUT_METHOD_SERVICE);  
		inputManager.showSoftInput(view, 0);  
		
	}
	
	/**
	 * 隐藏输入法
	 * @param c
	 * @param v
	 */
	public static void input_method_hide_ex(Activity c){
		if(c != null && c.getCurrentFocus().getWindowToken() != null){
			InputMethodManager inputMgr = (InputMethodManager) c.getSystemService(Context.INPUT_METHOD_SERVICE);
			if(inputMgr != null){
				inputMgr.hideSoftInputFromWindow(c.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 	
			}
		}
	}
//
	
	
	public static int getListViewHeightBasedOnPosition(ListView listView, int position) {
		  // 获取ListView对应的Adapter
		  ListAdapter listAdapter = (ListAdapter) listView.getAdapter();
		  if (listAdapter == null) {
			  return 0;
		  }
		  
		  int totalHeight = 0;
		  
		  for (int i = 0; i < position + 1; i++) { // listAdapter.getCount()返回数据项的数目
			  
			  View listItem = listAdapter.getView(i, null, listView);
			  listItem.measure(0, 0); // 计算子项View 的宽高
			  totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
		  }
		  
		  ViewGroup.LayoutParams params = listView.getLayoutParams();
		  return totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1))
				  + ScreenUtil.dip2px(10);	 
	}
	
	
//	public static void smoothScrollToPositionFromTop(final FloatingLayout mFloatingLayout, final AbsListView view, final int position, final int offY) {
//
//	    View child = getChildAtPosition(view, position);
//	    // There's no need to scroll if child is already at top or view is already scrolled to its end
//
//
//	    if ((child != null) && ((child.getTop() > 0) && !view.canScrollVertically(-1))) {
//	        return;
//	    }
//
//
//	    view.setOnScrollListener(new AbsListView.OnScrollListener() {
//	        @Override
//	        public void onScrollStateChanged(final AbsListView view, final int scrollState) {
//	            if (scrollState == SCROLL_STATE_IDLE) {
//	                view.setOnScrollListener(null);
//	                if(mFloatingLayout != null){
//	                	mFloatingLayout.attachToListView(view, new ScrollDirectionListener() {
//
//							@Override
//							public void onScrollUp() {
//
//							}
//
//							@Override
//							public void onScrollDown() {
//
//							}
//						});
//	                }
//	                // Fix for scrolling bug
//	                new Handler().post(new Runnable() {
//	                    @Override
//	                    public void run() {
//	                        if(view instanceof ListView){
//
//		                    	((ListView) view).setSelectionFromTop(position, offY);
//	                        }else{
//
//		                    	view.setSelection(position);
//	                        }
//	                    }
//	                });
//	            }
//	        }
//
//	        @Override
//	        public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount,
//	                                 final int totalItemCount) { }
//	    });
//
//	    // Perform scrolling to position
//	    new Handler().post(new Runnable() {
//	        @Override
//	        public void run() {
//	            view.smoothScrollToPositionFromTop(position, offY);
//	        }
//	    });
//	}
	

	public static View getChildAtPosition(final AdapterView view, final int position) {
	    final int index = position - view.getFirstVisiblePosition();
	    if ((index >= 0) && (index < view.getChildCount())) {
	        return view.getChildAt(index);
	    } else {
	        return null;
	    }
	}
}
